<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { getArchiveList, getArchiveDetail, updateArchive, restoreArchive } from '@/api/archive'
import { getOrganizationList, getPositionOptions, getPositionList } from '@/api/system'

const searchForm = ref({
  keyword: '',
  department: undefined,
  position: undefined,
})

const columns = [
  { title: '员工编号', dataIndex: 'code', key: 'code', width: 120 },
  { title: '姓名', dataIndex: 'name', key: 'name', width: 100 },
  { title: '性别', dataIndex: 'gender', key: 'gender', width: 80 },
  { title: '所属机构', dataIndex: 'organization', key: 'organization', width: 150 },
  { title: '职位', dataIndex: 'position', key: 'position', width: 120 },
  { title: '入职日期', dataIndex: 'joinDate', key: 'joinDate', width: 120 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 200 },
]

const dataSource = ref([])
const loading = ref(false)

// 分页相关
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
})

// 弹窗相关
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref({})

// 机构选项
const organizationOptions = ref([])
// 职位选项
const positionOptions = ref([])
// 职位 code 到 id 的映射
const positionCodeToIdMap = ref({})
// 职位 id 到 code 的映射
const positionIdToCodeMap = ref({})
// 职位名称到 code 的映射
const positionNameToCodeMap = ref({})

// 变更表单相关
const changeFormVisible = ref(false)
const changeFormLoading = ref(false)
const changeFormData = ref({})
const changeFormRef = ref(null)
const currentArchiveId = ref(null)

// 变更确认弹窗相关
const changeConfirmVisible = ref(false)
const changeConfirmForm = ref({
  changeType: '',
  changeContent: '',
  reason: '',
})
const changeConfirmFormRef = ref(null)

// 获取机构选项
const fetchOrganizationOptions = async () => {
  try {
    // 直接使用机构列表接口，因为它包含了 id 信息
    const listResponse = await getOrganizationList()
    if (listResponse && listResponse.list) {
      // 扁平化机构列表
      const flattenOrganizations = (orgs) => {
        const result = []
        orgs.forEach((org) => {
          result.push({
            id: typeof org.id === 'string' ? parseInt(org.id, 10) : org.id,
            code: org.code,
            name: org.name,
          })
          if (org.children && org.children.length > 0) {
            result.push(...flattenOrganizations(org.children))
          }
        })
        return result
      }

      const flattenedList = flattenOrganizations(listResponse.list)
      // 直接从列表构建选项，并保存 id 信息
      organizationOptions.value = flattenedList.map((org) => ({
        value: org.code,
        label: org.name,
        id: org.id, // 保存 id，这样就不需要映射了
      }))
    } else {
      organizationOptions.value = []
    }
  } catch (error) {
    console.error('获取机构选项失败:', error)
    organizationOptions.value = []
  }
}

// 获取职位选项（根据机构过滤）
const fetchPositionOptions = async (organizationCode) => {
  try {
    // 如果提供了机构 code，直接从选项中找到对应的 id
    let organizationId = undefined
    if (organizationCode) {
      const orgOption = organizationOptions.value.find((opt) => opt.value === organizationCode)
      if (orgOption && orgOption.id) {
        organizationId = orgOption.id
      }
      console.log('职位选项 - 机构查找:', {
        organizationCode,
        organizationId,
        orgOption,
      })
    }

    console.log('调用职位选项接口:', {
      organizationCode,
      organizationId,
    })

    // 优先使用 list 接口，因为它返回的数据更完整
    const listResponse = await getPositionList(undefined, organizationId)
    console.log('职位列表接口响应:', listResponse)

    if (listResponse && listResponse.list) {
      // 从 list 接口构建职位选项
      positionOptions.value = listResponse.list.map((position) => ({
        value: position.code,
        label: position.name,
      }))

      // 建立职位名称到 code 的映射
      listResponse.list.forEach((position) => {
        positionNameToCodeMap.value[position.name] = position.code
      })

      // 建立 code 到 id 和 id 到 code 的双向映射
      listResponse.list.forEach((position) => {
        const posId = typeof position.id === 'string' ? parseInt(position.id, 10) : position.id
        positionCodeToIdMap.value[position.code] = posId
        positionIdToCodeMap.value[posId] = position.code
      })
    } else {
      // 如果 list 接口失败，回退到 options 接口
      const optionsResponse = await getPositionOptions(organizationId)
      console.log('职位选项接口响应:', optionsResponse)

      if (optionsResponse && optionsResponse.list) {
        positionOptions.value = optionsResponse.list.map((item) => ({
          value: item.value,
          label: item.label,
        }))
        // 建立职位名称到 code 的映射
        optionsResponse.list.forEach((item) => {
          positionNameToCodeMap.value[item.label] = item.value
        })
      } else {
        positionOptions.value = []
      }
    }
  } catch (error) {
    console.error('获取职位选项失败:', error)
    positionOptions.value = []
  }
}

// 处理机构选择变化（查询表单）
const handleOrganizationChange = (value) => {
  // 如果先选了职位，再选机构，清空职位并刷新职位列表
  if (searchForm.value.position) {
    searchForm.value.position = undefined
  }
  // 根据选择的机构刷新职位列表
  fetchPositionOptions(value)
}

// 处理变更表单中机构选择变化
const handleChangeFormOrganizationChange = (value) => {
  // 如果先选了职位，再选机构，清空职位并刷新职位列表
  if (changeFormData.value.position) {
    changeFormData.value.position = undefined
  }
  // 根据选择的机构刷新职位列表
  fetchPositionOptions(value)
}

// 获取档案列表
const fetchArchiveList = async (page = 1, pageSize = 10) => {
  loading.value = true
  try {
    const params = {
      keyword: searchForm.value.keyword || undefined,
      department: searchForm.value.department || undefined,
      position: searchForm.value.position || undefined,
      page,
      pageSize,
    }

    // 移除 undefined 的字段
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getArchiveList(params)

    if (response && response.list) {
      dataSource.value = response.list.map((item) => ({
        ...item,
        key: item.id,
      }))
      // 更新分页信息
      pagination.value.total = response.total || 0
      pagination.value.current = response.page || page
      pagination.value.pageSize = response.pageSize || pageSize
    } else {
      dataSource.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取档案列表失败:', error)
    dataSource.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchArchiveList(pag.current, pag.pageSize)
}

const handleSearch = () => {
  pagination.value.current = 1
  fetchArchiveList(1, pagination.value.pageSize)
}

const handleReset = () => {
  searchForm.value = {
    keyword: '',
    department: undefined,
    position: undefined,
  }
  pagination.value.current = 1
  fetchArchiveList(1, pagination.value.pageSize)
}

const handleExport = () => {
  // TODO: 调用导出接口
  message.info('导出功能待实现')
}

// 获取档案详情
const fetchArchiveDetail = async (id) => {
  detailLoading.value = true
  try {
    const response = await getArchiveDetail(id)
    if (response) {
      detailData.value = response
    } else {
      message.error('获取详情失败')
      detailData.value = {}
    }
  } catch (error) {
    console.error('获取档案详情失败:', error)
    detailData.value = {}
  } finally {
    detailLoading.value = false
  }
}

// 打开详情弹窗
const handleViewDetail = async (record) => {
  detailVisible.value = true
  await fetchArchiveDetail(record.id)
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  detailVisible.value = false
  detailData.value = {}
}

// 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
  if (!date) return undefined
  if (dayjs.isDayjs(date)) {
    return date.format('YYYY-MM-DD')
  }
  return date
}

// 打开变更表单
const handleChange = async (record) => {
  changeFormLoading.value = true
  changeFormVisible.value = true
  currentArchiveId.value = record.id

  try {
    // 确保选项已加载（如果还没有加载）
    if (positionOptions.value.length === 0) {
      await fetchPositionOptions()
    }
    if (organizationOptions.value.length === 0) {
      await fetchOrganizationOptions()
    }

    const response = await getArchiveDetail(record.id)
    if (response) {
      // 将详情数据转换为表单数据
      // 根据 organizationId 和 positionId 查找对应的 code
      let organizationCode = response.organizationCode
      let positionCode = response.positionCode

      // 如果详情接口返回的是 id，需要转换为 code
      if (!organizationCode && response.organizationId) {
        const orgId =
          typeof response.organizationId === 'string'
            ? parseInt(response.organizationId, 10)
            : response.organizationId
        // 直接从选项中找到对应的 code
        const orgOption = organizationOptions.value.find((opt) => opt.id === orgId)
        organizationCode = orgOption?.value || response.organization
        console.log('机构ID转换:', {
          organizationId: response.organizationId,
          orgId,
          organizationCode,
          orgOption,
        })
      }
      if (!positionCode && response.positionId) {
        const posId =
          typeof response.positionId === 'string'
            ? parseInt(response.positionId, 10)
            : response.positionId
        positionCode = positionIdToCodeMap.value[posId]
        console.log('职位ID转换:', {
          positionId: response.positionId,
          posId,
          positionCode,
          map: positionIdToCodeMap.value,
        })
        if (!positionCode) {
          // 如果找不到 code，尝试从选项列表中查找
          const posOption = positionOptions.value.find((opt) => opt.label === response.position)
          positionCode = posOption?.value || response.position
        }
      }

      // 如果还是没有找到 code，使用返回的名称（可能是 code 本身）
      if (!organizationCode) {
        organizationCode = response.organization
      }
      if (!positionCode) {
        positionCode = response.position
      }

      console.log('最终表单数据准备:', {
        organizationCode,
        positionCode,
        response: {
          organization: response.organization,
          organizationId: response.organizationId,
          position: response.position,
          positionId: response.positionId,
        },
      })

      changeFormData.value = {
        employeeCode: response.code,
        name: response.name || '',
        gender: response.gender || '',
        idCard: response.idCard || '',
        birthDate: response.birthDate ? dayjs(response.birthDate) : undefined,
        ethnicity: response.ethnicity || '',
        politicalStatus: response.politicalStatus || '',
        maritalStatus: response.maritalStatus || '',
        phone: response.phone || '',
        email: response.email || '',
        emergencyContact: response.emergencyContact || '',
        emergencyPhone: response.emergencyPhone || '',
        organization: organizationCode || response.organization || '',
        position: positionCode || response.position || '',
        joinDate: response.joinDate ? dayjs(response.joinDate) : undefined,
        probationPeriod: response.probationPeriod || '',
        contractPeriod: response.contractPeriod || '',
        supervisor: response.supervisor || response.supervisorId || '',
        workLocation: response.workLocation || '',
        bankName: response.bankName || '',
        bankAccount: response.bankAccount || '',
      }
    } else {
      message.error('获取档案详情失败')
      changeFormVisible.value = false
    }
  } catch (error) {
    console.error('获取档案详情失败:', error)
    message.error('获取档案详情失败')
    changeFormVisible.value = false
  } finally {
    changeFormLoading.value = false
  }
}

// 关闭变更表单
const handleCloseChangeForm = () => {
  changeFormVisible.value = false
  changeFormData.value = {}
  currentArchiveId.value = null
  if (changeFormRef.value) {
    changeFormRef.value.resetFields()
  }
}

// 提交变更表单（先显示确认弹窗）
const handleChangeFormSubmit = async () => {
  try {
    await changeFormRef.value?.validate()
    // 打开变更确认弹窗
    changeConfirmVisible.value = true
    changeConfirmForm.value = {
      changeType: '',
      changeContent: '',
      reason: '',
    }
  } catch (error) {
    if (error?.errorFields) {
      return
    }
    console.error('表单验证失败:', error)
  }
}

// 提交变更确认
const handleChangeConfirmSubmit = async () => {
  try {
    await changeConfirmFormRef.value?.validate()

    if (!currentArchiveId.value) {
      message.error('无法获取档案ID')
      return
    }

    // 将 code 转换为 id
    // 首先尝试直接使用表单中的值作为 code
    let organizationCode = changeFormData.value.organization
    let positionCode = changeFormData.value.position

    // 如果表单中的值是名称而不是 code，需要查找对应的 code
    const orgOption = organizationOptions.value.find(
      (opt) => opt.value === organizationCode || opt.label === organizationCode,
    )
    if (orgOption) {
      organizationCode = orgOption.value
    }

    if (!positionCodeToIdMap.value[positionCode]) {
      // 尝试通过名称查找 code
      const posOption = positionOptions.value.find(
        (opt) => opt.value === positionCode || opt.label === positionCode,
      )
      if (posOption) {
        positionCode = posOption.value
      } else {
        // 尝试通过名称映射表查找
        positionCode = positionNameToCodeMap.value[positionCode] || positionCode
      }
    }

    // 直接从选项中找到对应的 id
    const organizationId = orgOption?.id
    const positionId = positionCodeToIdMap.value[positionCode]

    // 调试信息
    console.log('变更表单数据:', changeFormData.value)
    console.log('职位原始值:', changeFormData.value.position)
    console.log('职位 code (转换后):', positionCode)
    console.log('职位映射表:', positionCodeToIdMap.value)
    console.log('职位名称映射表:', positionNameToCodeMap.value)
    console.log('机构 code (转换后):', organizationCode)
    console.log('机构选项:', orgOption)

    if (!organizationId) {
      console.error('机构 code 未找到:', organizationCode)
      message.error(`无法获取机构ID，请检查机构选择。当前值: ${changeFormData.value.organization}`)
      return
    }

    if (!positionId) {
      console.error('职位 code 未找到:', positionCode)
      message.error(`无法获取职位ID，请检查职位选择。当前值: ${changeFormData.value.position}`)
      return
    }

    // 准备提交数据
    const submitData = {
      name: changeFormData.value.name,
      gender: changeFormData.value.gender,
      idCard: changeFormData.value.idCard,
      birthDate: formatDate(changeFormData.value.birthDate),
      ethnicity: changeFormData.value.ethnicity || undefined,
      politicalStatus: changeFormData.value.politicalStatus || undefined,
      maritalStatus: changeFormData.value.maritalStatus || undefined,
      phone: changeFormData.value.phone || undefined,
      email: changeFormData.value.email || undefined,
      emergencyContact: changeFormData.value.emergencyContact || undefined,
      emergencyPhone: changeFormData.value.emergencyPhone || undefined,
      organizationId: organizationId,
      positionId: positionId,
      joinDate: formatDate(changeFormData.value.joinDate),
      probationPeriod: changeFormData.value.probationPeriod || undefined,
      contractPeriod: changeFormData.value.contractPeriod || undefined,
      supervisorId: changeFormData.value.supervisor || undefined, // supervisorId 是可选的，如果详情接口返回的是名称，传 undefined
      workLocation: changeFormData.value.workLocation || undefined,
      bankName: changeFormData.value.bankName || undefined,
      bankAccount: changeFormData.value.bankAccount || undefined,
      changeType: changeConfirmForm.value.changeType,
      changeContent: changeConfirmForm.value.changeContent,
      reason: changeConfirmForm.value.reason,
    }

    // 移除 undefined 的字段
    Object.keys(submitData).forEach((key) => {
      if (submitData[key] === undefined || submitData[key] === null || submitData[key] === '') {
        delete submitData[key]
      }
    })

    const response = await updateArchive(currentArchiveId.value, submitData)
    console.log('档案变更响应:', response)

    message.success('变更申请已提交')
    changeConfirmVisible.value = false
    changeFormVisible.value = false
    changeFormData.value = {}
    changeConfirmForm.value = {
      changeType: '',
      changeContent: '',
      reason: '',
    }
    currentArchiveId.value = null

    // 刷新列表
    fetchArchiveList(pagination.value.current, pagination.value.pageSize)
  } catch (error) {
    if (error?.errorFields) {
      return
    }
    console.error('提交档案变更失败:', error)
  }
}

// 关闭变更确认弹窗
const handleCloseChangeConfirm = () => {
  changeConfirmVisible.value = false
  changeConfirmForm.value = {
    changeType: '',
    changeContent: '',
    reason: '',
  }
  if (changeConfirmFormRef.value) {
    changeConfirmFormRef.value.resetFields()
  }
}

// 恢复档案
const handleRestore = async (record) => {
  try {
    await restoreArchive(record.id)
    message.success('档案恢复成功')
    // 刷新列表
    fetchArchiveList(pagination.value.current, pagination.value.pageSize)
  } catch (error) {
    console.error('恢复档案失败:', error)
    // 错误信息已由 apiError.js 处理
  }
}

onMounted(async () => {
  // 确保机构选项和映射表都已加载完成
  await fetchOrganizationOptions()
  // 初始化时如果有选择的机构，根据机构加载职位
  if (searchForm.value.department) {
    await fetchPositionOptions(searchForm.value.department)
  } else {
    await fetchPositionOptions()
  }
  fetchArchiveList(1, pagination.value.pageSize)
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">人力资源档案查询</h1>
      <p class="page-desc">提供灵活多样的档案查询方式，支持多条件组合查询</p>
    </div>

    <div class="page-content">
      <div class="search-card">
        <div class="search-form">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-input v-model:value="searchForm.keyword" placeholder="员工编号/姓名" allow-clear />
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.department"
                placeholder="所属机构"
                allow-clear
                style="width: 100%"
                @change="handleOrganizationChange"
              >
                <a-select-option
                  v-for="option in organizationOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.position"
                placeholder="职位"
                allow-clear
                style="width: 100%"
                :disabled="!searchForm.department"
              >
                <a-select-option
                  v-for="option in positionOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-col>
          </a-row>
          <div class="search-actions">
            <a-space>
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button @click="handleReset">重置</a-button>
              <a-button @click="handleExport">导出</a-button>
            </a-space>
          </div>
        </div>
      </div>

      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag
                :color="
                  record.status === '已生效' || record.status === '在职'
                    ? 'green'
                    : record.status === '已恢复'
                      ? 'gold'
                      : record.status === '已删除'
                        ? 'red'
                        : 'default'
                "
              >
                {{ record.status }}
              </a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleViewDetail(record)"
                  >查看详情</a-button
                >
                <a-button type="link" size="small" @click="handleChange(record)">变更</a-button>
                <a-button
                  v-if="record.status === '已删除'"
                  type="link"
                  size="small"
                  @click="handleRestore(record)"
                >
                  恢复
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="档案详情"
      width="800px"
      :footer="null"
      @cancel="handleCloseDetail"
    >
      <a-spin :spinning="detailLoading">
        <div v-if="!detailLoading && Object.keys(detailData).length > 0" class="detail-content">
          <a-card title="基本信息" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="员工编号">{{ detailData.code }}</a-descriptions-item>
              <a-descriptions-item label="姓名">{{ detailData.name }}</a-descriptions-item>
              <a-descriptions-item label="性别">{{ detailData.gender }}</a-descriptions-item>
              <a-descriptions-item label="身份证号">{{ detailData.idCard }}</a-descriptions-item>
              <a-descriptions-item label="出生日期">{{ detailData.birthDate }}</a-descriptions-item>
              <a-descriptions-item label="民族">{{ detailData.ethnicity }}</a-descriptions-item>
              <a-descriptions-item label="政治面貌">{{
                detailData.politicalStatus
              }}</a-descriptions-item>
              <a-descriptions-item label="婚姻状况">{{
                detailData.maritalStatus
              }}</a-descriptions-item>
              <a-descriptions-item label="手机号码">{{ detailData.phone }}</a-descriptions-item>
              <a-descriptions-item label="邮箱">{{ detailData.email }}</a-descriptions-item>
              <a-descriptions-item label="紧急联系人">{{
                detailData.emergencyContact
              }}</a-descriptions-item>
              <a-descriptions-item label="紧急联系人电话">{{
                detailData.emergencyPhone
              }}</a-descriptions-item>
            </a-descriptions>
          </a-card>

          <a-card title="工作信息" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="所属机构">{{
                detailData.organization
              }}</a-descriptions-item>
              <a-descriptions-item label="职位">{{ detailData.position }}</a-descriptions-item>
              <a-descriptions-item label="入职日期">{{ detailData.joinDate }}</a-descriptions-item>
              <a-descriptions-item label="试用期">{{
                detailData.probationPeriod
              }}</a-descriptions-item>
              <a-descriptions-item label="合同期限">{{
                detailData.contractPeriod
              }}</a-descriptions-item>
              <a-descriptions-item label="直接上级">{{
                detailData.supervisor
              }}</a-descriptions-item>
              <a-descriptions-item label="工作地点">{{
                detailData.workLocation
              }}</a-descriptions-item>
              <a-descriptions-item label="状态">
                <a-tag
                  :color="
                    detailData.status === '已生效' || detailData.status === '在职'
                      ? 'green'
                      : detailData.status === '已恢复'
                        ? 'gold'
                        : detailData.status === '已删除'
                          ? 'red'
                          : 'default'
                  "
                >
                  {{ detailData.status }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="工资卡开户行">{{
                detailData.bankName
              }}</a-descriptions-item>
              <a-descriptions-item label="银行卡号">{{
                detailData.bankAccount
              }}</a-descriptions-item>
            </a-descriptions>
          </a-card>
        </div>
      </a-spin>
    </a-modal>

    <!-- 变更表单弹窗 -->
    <a-modal
      v-model:open="changeFormVisible"
      title="档案变更"
      width="900px"
      :confirm-loading="changeFormLoading"
      @ok="handleChangeFormSubmit"
      @cancel="handleCloseChangeForm"
    >
      <a-spin :spinning="changeFormLoading">
        <a-form
          v-if="!changeFormLoading"
          ref="changeFormRef"
          :model="changeFormData"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          layout="horizontal"
        >
          <a-card title="基本信息" class="section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="员工编号"
                  name="employeeCode"
                  :rules="[{ required: true, message: '员工编号不能为空' }]"
                >
                  <a-input
                    v-model:value="changeFormData.employeeCode"
                    placeholder="员工编号"
                    readonly
                    style="background-color: #f5f5f5; cursor: not-allowed"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="姓名"
                  name="name"
                  :rules="[{ required: true, message: '请输入姓名' }]"
                >
                  <a-input v-model:value="changeFormData.name" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="性别"
                  name="gender"
                  :rules="[{ required: true, message: '请选择性别' }]"
                >
                  <a-select v-model:value="changeFormData.gender" placeholder="请选择性别">
                    <a-select-option value="男">男</a-select-option>
                    <a-select-option value="女">女</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="身份证号"
                  name="idCard"
                  :rules="[{ required: true, message: '请输入身份证号' }]"
                >
                  <a-input v-model:value="changeFormData.idCard" placeholder="请输入身份证号" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="出生日期" name="birthDate">
                  <a-date-picker v-model:value="changeFormData.birthDate" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="民族" name="ethnicity">
                  <a-input v-model:value="changeFormData.ethnicity" placeholder="请输入民族" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="政治面貌" name="politicalStatus">
                  <a-select
                    v-model:value="changeFormData.politicalStatus"
                    placeholder="请选择政治面貌"
                  >
                    <a-select-option value="群众">群众</a-select-option>
                    <a-select-option value="团员">团员</a-select-option>
                    <a-select-option value="党员">党员</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="婚姻状况" name="maritalStatus">
                  <a-select
                    v-model:value="changeFormData.maritalStatus"
                    placeholder="请选择婚姻状况"
                  >
                    <a-select-option value="未婚">未婚</a-select-option>
                    <a-select-option value="已婚">已婚</a-select-option>
                    <a-select-option value="离异">离异</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="手机号码" name="phone">
                  <a-input v-model:value="changeFormData.phone" placeholder="请输入手机号码" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="邮箱" name="email">
                  <a-input v-model:value="changeFormData.email" placeholder="请输入邮箱" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="紧急联系人" name="emergencyContact">
                  <a-input
                    v-model:value="changeFormData.emergencyContact"
                    placeholder="请输入紧急联系人"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="紧急联系人电话" name="emergencyPhone">
                  <a-input
                    v-model:value="changeFormData.emergencyPhone"
                    placeholder="请输入紧急联系人电话"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <a-card title="工作信息" class="section-card" :bordered="false">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="所属机构"
                  name="organization"
                  :rules="[{ required: true, message: '请选择所属机构' }]"
                >
                  <a-select
                    v-model:value="changeFormData.organization"
                    placeholder="请选择所属机构"
                    @change="handleChangeFormOrganizationChange"
                  >
                    <a-select-option
                      v-for="option in organizationOptions"
                      :key="option.value"
                      :value="option.value"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="职位"
                  name="position"
                  :rules="[{ required: true, message: '请选择职位' }]"
                >
                  <a-select
                    v-model:value="changeFormData.position"
                    placeholder="请选择职位"
                    :disabled="!changeFormData.organization"
                  >
                    <a-select-option
                      v-for="option in positionOptions"
                      :key="option.value"
                      :value="option.value"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="入职日期"
                  name="joinDate"
                  :rules="[{ required: true, message: '请选择入职日期' }]"
                >
                  <a-date-picker v-model:value="changeFormData.joinDate" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="试用期" name="probationPeriod">
                  <a-select
                    v-model:value="changeFormData.probationPeriod"
                    placeholder="请选择试用期"
                  >
                    <a-select-option value="1个月">1个月</a-select-option>
                    <a-select-option value="3个月">3个月</a-select-option>
                    <a-select-option value="6个月">6个月</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="合同期限" name="contractPeriod">
                  <a-select
                    v-model:value="changeFormData.contractPeriod"
                    placeholder="请选择合同期限"
                  >
                    <a-select-option value="1年">1年</a-select-option>
                    <a-select-option value="3年">3年</a-select-option>
                    <a-select-option value="5年">5年</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="直接上级" name="supervisor">
                  <a-input v-model:value="changeFormData.supervisor" placeholder="请输入直接上级" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="工作地点" name="workLocation">
                  <a-input
                    v-model:value="changeFormData.workLocation"
                    placeholder="请输入工作地点"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="工资卡开户行" name="bankName">
                  <a-input v-model:value="changeFormData.bankName" placeholder="请输入开户行" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="银行卡号" name="bankAccount">
                  <a-input
                    v-model:value="changeFormData.bankAccount"
                    placeholder="请输入银行卡号"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-form>
      </a-spin>
    </a-modal>

    <!-- 变更确认弹窗 -->
    <a-modal
      v-model:open="changeConfirmVisible"
      title="确认变更"
      width="700px"
      @ok="handleChangeConfirmSubmit"
      @cancel="handleCloseChangeConfirm"
    >
      <a-form
        ref="changeConfirmFormRef"
        :model="changeConfirmForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item
          label="变更类型"
          name="changeType"
          :rules="[{ required: true, message: '请选择变更类型' }]"
        >
          <a-select v-model:value="changeConfirmForm.changeType" placeholder="请选择变更类型">
            <a-select-option value="基本信息变更">基本信息变更</a-select-option>
            <a-select-option value="岗位信息变更">岗位信息变更</a-select-option>
            <a-select-option value="状态变更">状态变更</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="变更内容"
          name="changeContent"
          :rules="[{ required: true, message: '请输入变更内容' }]"
        >
          <a-input
            v-model:value="changeConfirmForm.changeContent"
            type="textarea"
            :rows="4"
            placeholder="请详细描述变更内容"
          />
        </a-form-item>
        <a-form-item label="变更原因" name="reason">
          <a-input
            v-model:value="changeConfirmForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入变更原因"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.search-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.status-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: rgba(52, 199, 89, 0.1);
  color: #34c759;
}

.status-badge.inactive {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

.detail-content {
  padding: 8px 0;
}

.detail-section {
  margin-bottom: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.detail-section :deep(.ant-card-head) {
  background: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  padding: 16px 24px;
}

.detail-section :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.detail-section :deep(.ant-card-body) {
  padding: 24px;
}

.detail-section :deep(.ant-descriptions-item-label) {
  font-weight: 500;
  background: #f5f5f5;
}

.section-card {
  margin-bottom: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.section-card :deep(.ant-card-head) {
  background: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  padding: 16px 24px;
}

.section-card :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.section-card :deep(.ant-card-body) {
  padding: 24px;
}
</style>
